package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// 跨域中间件
func CorsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")  // *表示允许所有域名的请求
		c.Writer.Header().Set("Access-Control-Max-Age", "86400")   // 返回时间
		c.Writer.Header().Set("Access-Control-Allow-Methods", "*") // 访问方法,get,post等，*表示所有方法
		c.Writer.Header().Set("Access-Control-Allow-Headers", "*") // 允许的请求头
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

		if c.Request.Method == http.MethodOptions {
			c.AbortWithStatus(200)
		} else {
			c.Next()
		}
	}
}
